
\chapter{Pattern Enforcer}
\label{chap:pattern-enforcer}

%-------------------------------------------------------------------------------------------------
%-------------------------------------------------------------------------------------------------
%-------------------------------------------------------------------------------------------------
\section{Features}
\label{sec:patternenforcerfeatures}

\paragraph{Patterns constraints specification}
\subparagraph*{}
Pattern Enforcer is a tool for developers and it is expected to be used by developers 
only during the development process, not in the production builds. Because of these facts 
we decided to provide internal type safe C\# Domain Specific Language (DSL, \cite{fowler2010domain}) 
for constraints configuration instead of xml based configuration or 
custom constraint language. 

\subparagraph*{}
\emph{
In \cite{fowler2010domain}, Martin Folwer defines DSL as a computer programming 
language of limited expressiveness focused on a particular domain.
There are two types of DSLs -- internal and external. External DSLs are 
completely new languages with their own custom syntax, while internal DSLs 
are embedded into existing general purpose language such as C\#, Java or Ruby 
by providing specific public API.
}

\subparagraph*{}
Type safe DSLs use contructs that can be verified by a compiler rather than 
strings with special internal syntax that could be verified only during 
the runtime or by a additional tool. For example, NHibernate ORM framework 
(\cite{nhibernate:Online})
has such API for a definition of objects to database schema mapping. 
Instead of expressing the names of properties as a strings, 
NHibernate exploits the C\#'s feature of lambda expressions for this purpose 
and thus existence of properties used in the mapping is verified by a compiler. 
For a better idea of this approach, figure \ref{fig:nhibapi} shows a 
short example of the NHibernate DSL.

	\begin{figure}[h]				
		\begin{minted}[bgcolor=codebg]{csharp}
var mapper = new ModelMapper();
mapper.Class<RegisteredUser>(mapping =>
{
    mapping.Id(x => x.Id, map => map.Column("MyClassId"));
    mapping.Property(x => x.Username, map => map.Length(150));
});
		\end{minted}		
		\caption{Example of internal type safe DSL.}
		\label{fig:nhibapi}
	\end{figure}

\subparagraph*{}
Usage of type safe DSLs also enables integrated development environments 
support. Namely intellisense support could make the development more effective 
and could bring better experience for developers who don't know the DLS syntax yet, 
because they can see all the possibilities in the intellisense window together 
with their API documentation. On the other hand, after every change, the code 
has to be recompiled and the assembly must be deployed, which is not always 
possible. Xml based configuration or external DSL might provide more flexible 
solution in such case. 

\subparagraph*{}
DSLs usually laverages a technique called a Fluent API, which means that a 
method returns an object on which a user is expected to invoke another 
method. This chaining of methods may make the API more self describing, 
becuase the code can be than read almost as a sentence. The exmple of Pattern  
Enforcer unit tests Fluent API is show in figure \ref{fig:fluentapi}.

	\begin{figure}[h]				
		\begin{minted}[bgcolor=codebg]{csharp}
patternEnforcer.AssertThat<WidgetContainer>().IsComposite();
		\end{minted}		
		\caption{Example of Fluent API.}
		\label{fig:nhibapi}
	\end{figure}
	
\subparagraph*{}
For specifying constraints about a design pattern instance we need 
a data structure that would capture the information about the roles in this 
design pattern instance. By the term design pattern instance we 
mean concrete classes that implement the pattern, but not thier 
particular instances. For better ilustration, an instance of 
the \pattern{Composite} pattern is given in figure \ref{fig:composite}. 
From the structural point of view the \pattern{Composite} pattern has two roles: 
the \pattern{Composite} class (in this instance represented by 
the \inlinecode{WidgetComposition} class) and
the \pattern{Component} interface (the \inlinecode{IWidget} interface), 
which should by implemented by the \pattern{Composite} class. 

	\begin{figure}[h]				
		\begin{minted}[bgcolor=codebg]{csharp}
public class WidgetComposition : IWidget
{
	private IList<IWidget> children;
	public int Width {
		get { return children.Sum(x => x.Width); }
	}
}
		\end{minted}		
		\caption{Example of the \pattern{Composite} pattern instance.}
		\label{fig:composite}
	\end{figure}

In Patterns4Net, we represent patterns as a Common Language Runtime (CLR) 
classes derived from the \inlinecode{IPattern} interface. A pattern class should 
contain properties whose values represent the participants of the pattern. 
In case of the \pattern{Composite} pattern, the class for its representation 
would contain properties "Composite" and "Component". An instance of such class 
representing the pattern instance from our example would contain a reference 
to the \inlinecode{WidgetComposition} type as the value of the "Composite" property  
and a reference to the \inlinecode{IWidget} interface as the value of the "Component" 
property. 

\subparagraph*{}
References to types are represented as instances of the 
\inlinecode{TypeReference} or the \inlinecode{TypeDefinition} 
classes from library Mono Cecil, which are similar to the 
\inlinecode{System.Type} type from the standard library. This is because we 
use Mono Cecil for processing of .NET assemblies\footnote{Reasons why we have chosen Mono Cecil 
and more detailed information about it are presented in the subsection \ref{subsec:cil}}.
A participant of a pattern might be also a method (represented as 
\inlinecode{MethodDefinition} or \inlinecode{MethodReference} from Mono Cecil) 
as in the \pattern{Simple Factory Method} pattern. Generally speaking class 
representing a pattern might contain whatever the pattern author finds useful 
but public properties of types listed above have a special meaning for Patterns4Net. 
Figure \ref{fig:compositedef} demonstrates an example of the \pattern{Composite} 
pattern definition. 

	\begin{figure}[h]				
		\begin{minted}[bgcolor=codebg]{csharp}
public class Composite : IPattern
{
	public TypeDefinition Composite { get; set; }
	public TypeReference Component { get; set; }
	// The Name is required by IPatter interface
	public string Name { 
		get { return "Composite"; } 
	}
}
		\end{minted}		
		\caption{The \pattern{Composite} pattern definition for Patterns4Net.}
		\label{fig:compositedef}
	\end{figure}
		
\subparagraph*{}
Now when we have the strongly typed representation of design patterns instances, 
we can build a type safe DSL for their constraints specification. 
In our conception, a constraint is any boolean function that takes a pattern 
instance as a parameter and returns a boolean value, which indicates whether 
the pattern instance conforms to the constraint or not. However, Pattern Enforcer 
provides a DSL to make the specification of constraints easier than that. 
The key part is that it enables to specify constraints as lambda functions 
(we call such function a "check"). Check may be performed on the whole 
pattern instance, than the parameter of the lambda function will be the 
object representnig the pattern. These checks may verify relations between 
roles, for example that the \pattern{Composite} class implements the 
\pattern{Component} interface. Users can also set up checks for a 
specific role of a pattern instance. In such case, the Pattern Enforcer API 
provides a method to select the specific property of the pattern instance object 
with a lambda function the same way NHibernate uses lambda functions 
for selecting properties. After the property is selected, user can create 
check only for the value of the selected property. Finally users can also 
select specific methods of the selected type to provide a check for each of them. 
The selection of these methods is also done using a lambda function. 
To summarize it up: user can 
select a subject of the check, using lambda functions, and than he enters 
the check itself again as a lambda function, which takes the subject of the 
check as a parameter. For better idea, an example is 
shown in figure \ref{fig:selectionapi}.

	\begin{figure}[h]				
		% ,linenos=true
		\begin{minted}[bgcolor=codebg]{csharp}
// we want to work with the Composite role
this.Type(composite => composite.Composite)	
// we want to check all its non-private methods
.Methods(method => method.IsPublic || method.IsProtected) 
// on each of them, we perform the following check
.Check((composite, method) => method.CallsAnyOf(pattern.Component),
	(composite, method) => "An error in " + method.Name));
		\end{minted}		
		\caption{An example of constraints configuration in Pattern Enforcer.}
		\label{fig:selectionapi}
	\end{figure}

\subparagraph*{}
A check expression might be anything, which enables wide range of possibilities 
for experienced users, but Pattern Enforcer provides easy to use extensions 
to underlying Cecil's API. \inlinecode{CallsAnyOf} is an example of such 
extension, which returns \inlinecode{true} iff the method invokes a member 
of given class. Basically these extensions are designed to enable 
straightforward specification of most of the predicates presented in 
the section \ref{sec:patterns-formalization}.

\paragraph*{Supported patterns}
\subparagraph*{}
As we claim in the section \ref{sec:patterns-formalization} constraints for 
built-in patterns were chosen rather less restrictively than in other 
tools of this type. The aim was to enforce those aspects that are strongly 
significant to given pattern and the implementation without them cannot be 
clearly called as an implementation of this pattern. For example the 
\pattern{Factory Method} pattern, whose main participant is the 
\patternrole{Factory Method} itself, would make no sense if the actual 
\patternrole{Factory Method} was void. On the other hand, to enforce that the 
method's body contains only a constructor invocation and a return statement, 
seems to us as an inappropriate restriction, because the developer 
might want to prepare some data structures before returning the \patternrole{Product} 
of the \pattern{Factory Method}. Patterns supported by Pattern Enforcer by 
default are listed in the appendix A.

\subparagraph*{}
Relatively unrestrictive API for patterns constraints specification allow us 
also to provide more advanced verification than only verification of 
structural aspects. This is the case of the \pattern{Immutable} pattern. 
The verification of it's implementation checks that the \pattern{Immutable} 
class does not allow to change internal state of it's instance once it is 
available to the "outside world". What does this bring us? Simple immutability 
in C\# can be enforced by specifying the class's fields as readonly, but 
this disables the creator of the class to provide a 
\pattern{Simple Factory Method} that would do some changes to 
the \pattern{Immutable} class instance, before it 
returns it to the "outside world". Also backing fields of auto-implemented 
properties, which brings a notable simplification of implementation of 
simple properties, cannot be specified as read-only. 


\paragraph*{User Interface}
\subparagraph*{}
Pattern Enforcer provides usual command line interface and MSBuild task that 
can be used in MSBuild scripts. Visual Studio project formats (e.g., *.csproj) 
are basically MSBuild scripts, so Pattern Enforcer can be easily included in 
build process. In both cases the input is .NET assembly and output is 
text printed to standard output in one of three supported formats 
(plain text, Visual Studio format or xml). 

\subparagraph*{}
Besides these two user interfaces, Pattern Enforcer provides public API 
designed to be used inside unit tests. Through this API, developers can invoke 
whole Pattern Enforcement checking process based on patterns annotations, 
or they can invoke a single check of conformance of a specific class to 
a specific pattern. In the former case, it is not required to decorate 
the checked class with patterns attributes.

\paragraph{Configuration}
\subparagraph*{}
The configuration of constraints that are enforced on patterns implementations 
can only be done in code. However, Pattern Enforcer CLI and MSBuild task can be 
configured using xml. In this configuration, user can 
turn off all checks of given pattern and provide paths to assemblies 
containing custom patterns specification. Checking by Pattern Enforcer 
can be turned off also by special attribute \inlinecode{PatternEnforcerIgnoreAttribute}, 
which has string property \inlinecode{Justification}, where developers 
should provide a description why they have disabled the checks on this class or 
method.


%-------------------------------------------------------------------------------------------------
%-------------------------------------------------------------------------------------------------
%-------------------------------------------------------------------------------------------------
\section{Usage}
\label{sec:patternenforcerusage}
\paragraph{}
\subparagraph*{}
If a user wants to take advantage of Pattern Enforcer, one possible way to 
achieve it is to decorate his types with pattern attributes. 
For this it is required to add reference 
to the \emph{Patterns4Net.Attributes.dll} assembly in the project. This 
assembly contains only attributes definitions, thus it's footprint should be 
minimal. It is build for .NET version 2.0, so Pattern Enforcer can be basically 
used in projects build for older versions of the .NET. 
When the reference is added, the types can be decorated with attributes 
from the namespace \inlinecode{Patterns4Net.Attributes}. A code 
example is provided in \ref{fig:wrongcomposite}. Here the 
\inlinecode{WidgetComposition} class is decorated with the \inlinecode{Composite} 
attribute, which also allows us to provide a \pattern{Component} type as a 
constructor parameter. Explicit specification of a \pattern{Component} type 
is requried when a \pattern{Composite} class implements more than one interface, 
otherwise the \pattern{Component} type can be inferred.

	\begin{figure}[h]				
		\begin{minted}[bgcolor=codebg]{csharp}
using Patterns4Net.Attributes;
[Composite(typeof(IWidget))]
public class WidgetComposition : IWidget, ICloneable
{
	private IList<IWidget> children;
	int IWidget.Width {
		get { return 10; }
	}
	// ...
}
		\end{minted}		
		\caption{Example of internal type safe DSL.}
		\label{fig:wrongcomposite}
	\end{figure}
	
\subparagraph*{}
As we can see, the implementation of the \pattern{Composite} pattern is 
not valid in this case, because the getter method of the \inlinecode{Width} 
property is not using the \inlinecode{children} collection. Pattern Enforcer 
can ba run outside the Visual Studio or inside the Visual Studio. 
Firstly we will describe the first option. When the Visual Studion project is 
built, there should be a resulting assembly in the output folder 
(usually \{project folder\}\textbackslash{}bin\textbackslash{}Debug). 
Say it's name is \emph{EnforcerExample.dll}. 
Than if the \emph{pattern-enforcer.exe} is run from command line supplyed with  
a path to \emph{EnforcerExample.dll} as an argument, it should produce the output 
shown in figure \ref{fig:enforcercmd}.

	\begin{figure}
		\mbox{\includegraphics[width=\textwidth]{images/enforcer-cmd.eps}}
		\caption{The output of Pattern Enforcer for the 
		\inlinecode{WidgetComposition} class.}
		\label{fig:enforcercmd}
	\end{figure}

\subparagraph*{}
Besides the direct execution of \emph{pattern-enforcer.exe} Pattern Enforcer can 
be integrated more tightly into the build process in Visual Studio. 
Visual Studio project files are basically MSBuild scripts, 
so the only thing a user has to do is to add a reference to Pattern 
Enforcer MSBuild task and invoke it in the AfterBuild target, which, as 
its name indicates, gets always executed after the source code is built.
To enable this integration, it is needed to to open the project file 
\emph{EnforcerExample.csproj} in any text editor, find the xml root 
element \inlinecode{Project} and just below it, insert a 
\inlinecode{UsingTask} tag, where the location of 
the \emph{PatternEnforcer.MSBuildTask.dll} assembly should be specified. 
Next the AfterBuild target should be located (it should be commented out and 
placed near the end of the file), it should be uncommented, 
and an invocation of the Pattern Enforcer task should be inserted as 
it's child element. The figure \ref{fig:msbuild} shows the xml code and also 
a screenshot of Visual Studio displaying the warnings.

	\begin{figure}[h]				
		\begin{minted}[bgcolor=codebg,tabsize=2,fontsize=\small]{xml}
<Project ToolsVersion="4.0" DefaultTargets="..." xmlns="...">
  <!-- Includes the PatternEnforcerTask -->
  <UsingTask TaskName="PatternEnforcerTask" 
    AssemblyFile=".\a\path\to\PatternEnforcer.MSBuildTask.dll"/>
  
  <!-- ... -->
  <PropertyGroup>
    <PatternAssemblies>
      $(OutputPath)/$(AssemblyName).dll;
    </PatternAssemblies>
  </PropertyGroup>    
  <Target Name="AfterBuild">
    <PatternEnforcerTask 
      ToolPath="..\a\path\to\pattern-enforcer-executable\" 
      ConfigFile=".\enforcer-config.xml"
      ShowErrorsAsWarnings="true"
      InputAssemblies="$(PatternAssemblies)">
    </PatternEnforcerTask>  
  </Target>  
</Project>
		\end{minted}	
		\mbox{\includegraphics[width=\textwidth]{images/enforcer-vs-errors.eps}}		
		\caption{Integration of Pattern Enforcer and Visual Studio 2010.}
		\label{fig:msbuild}
	\end{figure}

\paragraph{Unit tests}
\subparagraph*{}
The second possible way of taking advantage of Pattern Enforcer does not 
require to annotate classes with pattern attributes. Instead the relation 
between a concrete pattern and it's roles is constructed in an automatized test. 
Pattern Enforcer provides the \inlinecode{PatternEnforcerContext} class whose 
instance represents an assembly loaded into memory and prepared for 
execution of Pattern Enforcer checks. It is recommended to set up this 
object in the test fixture\footnote{This term is used by the NUnit 
framework (\cite{nunit:Online}), some of other xUnit frameworks also use 
the term "test suite" instead of a test fixture.}
set up method, which is a method that gets executed only once 
before any test from the test fixture is executed. 
The \inlinecode{PatternEnforcerContext} provides a method \inlinecode{AssertThat}, 
which has one generic parameter. This method returns an object that provides 
methods with names Is\{PatternName\}, which perform the check of 
conformance to given pattern. The type selected with call to 
\inlinecode{AssertThat} is used as main role of the pattern, other additional 
required information, if needed, are supplied as parameters of the 
Is\{PatternName\} method. The figure \ref{fig:testfixture} shows an example of such test 
fixture using the NUnit framework (\cite{nunit:Online}).

	\begin{figure}[h]				
		\begin{minted}[bgcolor=codebg,fontsize=\small]{csharp}
[TestFixture]
public class WidgetCompositionTests : IWidget, ICloneable
{
  private PatternEnforcerContext patternEnforcer;
  [FixtureSetUp]
  public void SetUpFixture() {
    this.patternEnforcer = 
      PatterEnforcerContext.Create("EnforcerExample.dll");
  }  
  [Test]
  public void WidgetComposition_Is_Composite() {
    this.patternEnforcer
      .AssertThat<WidgetComposition>()
      .IsComposite(typeof(IWidget));
  }
}
		\end{minted}		
		\caption{Example of an automatized test that invokes Pattern Enforcer.}
		\label{fig:testfixture}
	\end{figure}

\paragraph{Specification of custom pattern}
\subparagraph*{}
There are two possibilities to define a pattern and constraints that will be 
enforced on it's implementation. The first one is more complex, but provides 
better flexibility, and thus is used internally by Pattern Enforcer. The 
second one is more simple and is designed to provide an easier instrument to 
create user-defined patterns. The first approach is described in the section 
\todo{section number}. Here we describe how to use the second one. 
We will describe an implementation of pattern we will call \pattern{Base Caller}. 
It has two roles: the Target class and the Target's base class. The constraint 
we wil specify is that the Target class is required to invoke the corresponding 
base methods in overridden methods bodies.

\subparagraph*{}
Custom pattern is represented by a class that inherits from 
the \inlinecode{IPattern} interface and it is recommended to also implement the 
\inlinecode{IPatternAttribute} interface, which is just marker for pattern 
attributes. This class is used for representation of the pattern and at the same 
time as an attribute for annotating the pattern instances in code. 

\subparagraph*{}
The \inlinecode{IPattern} interface requires just 
the getter of the property named \inlinecode{Name} and the getter of 
\inlinecode{AbstractionLevel} property, which is used by Architecture 
Explorer (\inlinecode{null} can be used as default value). 
The value of the \inlinecode{Name} property should be a human readable name 
of the pattern, which may contain any characters including 
spaces. The \inlinecode{IPattern} interface does not require any other 
properties, but the creator of the pattern should add other properties for 
representing the pattern participants, in this case the Target and 
it's base class. Because these properties should contain references to 
other types, they will be of type \inlinecode{TypeDefinition}. 
The implementation is shown in figure \ref{fig:custompattern1}.

	\begin{figure}[h]				
		\begin{minted}[bgcolor=codebg]{csharp}
[TestFixture]
public class BaseCaller : IPattern, IPatternAttribute
{
	string IPattern.Name {
		get { return "Base Caller"; }
	}	
	public TypeDefinition TargetType { get; set; }
	public TypeDefinition BaseType { get; set; }
}
		\end{minted}		
		\caption{Example of an automatized test that invokes Pattern Enforcer.}
		\label{fig:testfixture}
	\end{figure}

\subparagraph*{}
During the processing of patterns attributes, Patterns4Net needs to 
reconstruct the \inlinecode{BaseCaller} from CIL metadata. 
The metadata does not contain an instance of the attribute, 
instead it contains only values of constructor arguments used for its 
instantiation and names and the values of the properties that were assigned. 
For example, metadata for the \inlinecode{PatternEnforcerIgnoreAttribute} in 
figure \ref{fig:attributeexample} would contain: zero constructor arguments, 
because the parameterless constructor of \inlinecode{PatternEnforcerIgnoreAttribute} 
was used; and one property with name \inlinecode{Justification} and it's value.

	\begin{figure}[h]				
		\begin{minted}[bgcolor=codebg]{csharp}
[PatternEnforcerIgnoreAttribute(
Justification="A constant value")]
public class AnnotatedClass
{
}
		\end{minted}		
		\caption{A code example to illustrate CIL metadata for attributes.}
		\label{fig:attributeexample}
	\end{figure}

\subparagraph*{}
For the purpose of reconstruction of pattern attributes from CIL metadata, 
classes that implement both the pattern and it's attribute are required to 
define a constructor with one parameter of type \inlinecode{IDictionary<string, object>}
\footnote{More technical reasons that lead to this decision are given in 
section \ref{sec:enforcer-architecture}}. The class should be able to 
reconstruct it's instance from this dictionary, which provides the following data:
\begin{itemize}
	\item{Constructor Arguments -- indexed by the number of position. 
	For example, the first argument, if any, will be under the index \inlinecode{"0"}.}
	\item{Attribute's target -- a \inlinecode{TypeReference} instance that 
	contains a reference to the type that was decorated with this attribute. 
	This value is available under the index \inlinecode{"Target"}.}	
	\item{Assigned properties -- the remaining entries of the dictionary are name-value 
	pairs representing the properties. If the property is of type 
	\inlinecode{System.Type}, than it's actual value will 
	be \inlinecode{TypeReference} from Mono Cecil 
	refering to the same type.}		
\end{itemize}
The implementation of such constructor for the \inlinecode{BaseCaller} class 
is shown in figure \ref{fig:basecallerctor}. An instance of 
\inlinecode{TypeReference} class can be converted to corresponding 
\inlinecode{TypeDefinition} instance using method 
\inlinecode{Resolve()} as in the example.

	\begin{figure}[h]				
		\begin{minted}[bgcolor=codebg]{csharp}
public class BaseCaller : IPattern, IPatternAttribute
{
	public BaseCaller(IDictionary<string, object> values) {
		var targetRef = (TypeDefinition)values["Target"];
		this.TargetType = targetRef.Resolve();
		this.BaseType = this.TargetType.BaseType.Resolve();
	}
	// ... as before
}
		\end{minted}		
		\caption{Example of an automatized test that invokes Pattern Enforcer.}
		\label{fig:basecallerctor}
	\end{figure}
	
\subparagraph*{}
The pattern, as declared in figure \ref{fig:basecallerctor}, can be used 
for annontation of classes that implement our \pattern{Base Caller} pattern. 
However, to verify that such class invokes corresponding base methods in 
overridden methods' bodies the last two things are needed. First is to 
implement the \inlinecode{IPatternCheckerProvider} interface, defined in 
the assembly \emph{PatternEnfocer.Core.dll}. This interface contains one 
method \inlinecode{GetChecker}, which should return a constraints 
checker for the pattern. The last thing needed is to create the checker itself. 
The \inlinecode{FluentPatternChecker} class, which implements the DSL we 
have described above, is inteded to be the base class for pattern checkers, 
althought a minimal pattern checker has only to implement the 
\inlinecode{IPatternChecker} interface. The implementation of a checker for 
the \pattern{Base Caller} pattern is similar to the one we describe 
in the section \ref{sec:patternenforcerfeatures}. 
For completeness of the example, figure \ref{fig:basecallerchecker} shows the 
final implementation of the \pattern{Base Caller} pattern.

	\begin{figure}[h]				
		\begin{minted}[bgcolor=codebg, fontsize=\small]{csharp}
public class BaseCaller : IPatternCheckerProvider, ...
{
  // ... same as before    
  public IPatternChecker GetChecker() {
    return new Checker();
  }
  
  private class Checker : FluentPatternChecker<BaseCaller> {
    public Checker() {
      this.Type(pattern => pattern.TargetType)
          .Methods(method => method.OverridesBaseMethod())
          .Check((pattern, method) =>
                    method.GetMethodCalls() != null &&
                    method.GetMethodCalls().Any(call =>
                      call.HasTargetObject &&
                      call.TargetObject.IsThisParameter &&
                      call.Method.DeclaringType.IsEqual(
					      pattern.TargetBase) &&
                      call.Method.Name == method.Name),
                 (pattern, method) =>
                     string.Format(
                       "Method {0} does not invoke the base method.",
                       method.Name));
    }
  }
}
		\end{minted}		
		\caption{Definition of a checker for custom pattern.}
		\label{fig:basecallerctor}
	\end{figure}
	
\subparagraph*{}
Finally Pattern Enforcer has to be informed that it should load the assembly 
that contain the custom pattern definition and search it for custom patterns 
definitions. For this purpose, it is required to provide the assembly 
location in Pattern Enforcer configuration file. A configuration is an xml 
file, the \inlinecode{pattern-enforcer-config.xsd} file with definition of 
it's structure is supplied with Patterns4Net. The location of a configuration 
file is provided to Pattern Enforcer as a command line option, or the 
parameter of the MSBuild task.


%-------------------------------------------------------------------------------------------------
%-------------------------------------------------------------------------------------------------
%-------------------------------------------------------------------------------------------------
\section{Architecture}
\label{sec:enforcer-architecture}

%-------------------------------------------------------------------------------
%-------------------------------------------------------------------------------
\subsection{Overall architecture}

\paragraph*{}
\subparagraph*{}
In this section about Pattern Enforcer architecture, we also describe 
common infrastructure used by both Pattern Enforcer and Architecture Explorer 
tools. Patterns4Net tools are developed in .NET platform version 4, 
mostly in the C\# 4.0 language. Xml technologies are also used. 
All xml formats have their corresponding xsd file.

\paragraph{Visual Studio solution layout}
\subparagraph*{}
In the figure \ref{fig:solution} we can see the layout of Visual Studio 
solution used for Patterns4Net development. 
\begin{figure}[h]
  \mbox{\includegraphics[width=65mm]{images/solution.eps}}
  \caption{The layout of Visual Studio solution.}
  \label{fig:solution}
\end{figure}

\subparagraph*{}
Projects that start with "Patterns4Net.PaternEnforcer" are related to 
Pattern Enforcer tool. Classes that provide the core functionality of 
Pattern Enforcer and classes that form the unit-testing public API are 
located in the \patternsproj{Patterns4Net.PatternEnforcer.Core} project. 
The output of the \patternsproj{Patterns4Net.PatternEnforcer.Cmd} project is 
command line interface for the Pattern Enforcer and the project 
\patternsproj{Patterns4Net.PatternEnforcer.MSBuildTask} is 
implementation of the task for the MSBuild engine. Core functionality and 
unit-testing API of Pattern Enforcer are decoupled from command line interface 
and MSBuild task into separate project, and thus separate assembly, 
because the Pattern Enforcer core functionality is used also in 
\patternsproj{Patterns4Net.ArchitectureExplorer}. The resulting 
assembly is also ment to be referenced by users in their unit-testing 
projects and if it had an .exe suffix, although perfectly valid assembly 
that can be referenced, unusual suffix might confuse some users.

\subparagraph*{}
Project \patternsproj{Patterns4Net.ArchitectureExplorer} contains the code 
of the Architecture Explorer GUI tool. The GUI is done in Windows Presentation 
Foundation (WPF) framework. In this project, besides C\# classes, also 
XAML\footnote{Extensible Application Markup Language} files are included.

\subparagraph*{}
Automated tests are used during the development of Patterns4Net. These 
tests are located in the \patternsproj{Patterns4Net.Tests} project. 
This project aggregates tests for classes in all the other projects, 
because we don't need to separate the tests into several projects 
and a lower number of projects speeds up the build process. 

\subparagraph*{}
The classes that deal with the discovery of patterns meta-data are located 
in the \patternsproj{Patterns4Net.Core} project. 
Although we use only Patterns4Net attributes at the moment, 
process of discovering patterns metadata for classes and methods is 
fully extensible. 

\subparagraph*{}
Finally the project \patternsproj{Patterns4Net.Patterns} contains only 
classes that represent the Patterns4Net attributes. These classes 
inherit from \inlinecode{System.Attribute} class and they are very simple, 
hence we don't necessarily need to take advantage of the advanced features of 
C\# 4.0. This enables us to set the target framework version to 2.0, which 
means that the resulting assembly can be referenced and used 
in older .NET projects as well.

%maybe image/graph of projects dependencies

\paragraph{General principles}
\subparagraph{Automated tests.} 
Every software should be tested. Besides manual testing, usually a time 
consuming task, there is also a possibility to automate some tests, 
which means that their execution is controlled by a software and 
the software reports eventual errors. Execution of such tests lasts 
in seconds, so they can be executed quite often. Some of the code of 
Patterns4Net is tested this way. For automated tests the NUnit framework 
(\cite{nunit:Online}) is used. 

\subparagraph*{Extensibility.}
For better support of extensibility the Managed Extensibility 
Framework (MEF, \cite{mef:Online}) is used. The MEF provides discovery and 
composition capabilities that are employed in plugins mechanism of Patterns4Net.

\subparagraph*{Code Contracts.} 
Most of the classes define their contracts using Microsoft Code Contracts 
(\cite{code-contracts:Online}). Contracts help us to find issues earlier. 
Exception is thrown typically during the pre-conditions check, which is 
the real cause of the problem, rather than later on a source code line 
that expects valid input parameters. Code Contracts also serve as a complement 
to the API documentation.

\subparagraph*{Design Patterns.} Patterns4Net might be considered as a 
first example of it's own usage, because Patterns4Net code is annotated 
with patterns attributes.


%-------------------------------------------------------------------------------
%-------------------------------------------------------------------------------
\subsection{CIL processing}
\label{subsec:cil}

\paragraph{}
\subparagraph*{}
The analysis of the source code could be done using the original textual 
source code, which can be parsed and represented as an abstract syntax tree (AST). 
With this approach it is much easier to reconstruct higher level information 
such as actual parameters for a method invocation. On the other hand, available 
parsers not always support all of the most current language features and 
parsing of a source code of a specific language might restrict us to support 
only the one language or, if we used parsers capable of parsing more languages 
into the same AST, we would still have to deal with some language specific 
constructs.

\subparagraph*{}
The other option, which we have chosen, is to analyse the intermediate 
language, in case of the .NET 
it is Common Intermediate Language (CIL), sometimes called Microsoft 
Common Intermediate Language (MSIL). The structure of CIL is more stable 
than, for example, the syntax of C\#. The latest version of CIL standard 
\cite{ecma2010tg3} from 2010 has the same instruction set as the previous 
version from 2006. The version from 2010 only extends semantics and 
verification rules for some of the instructions. Another adavantage is 
that intermediate language is produced by all the compilers for .NET, 
thus Patterns4Net can be theoretically used also for Visual Basic.NET, 
IronRuby, IronPython and others, alhought we had tested it only on C\#. 
One of the disadvantages of this approach is that the CIL is stack based 
lower level language and reconstruction of some constructs, such as actual 
parameters for a method invocation, requires special effort.


\paragraph{Library for CIL parsing}
\subparagraph*{}
There are three popular, publicly available libraries that could be used 
to parse .NET assemblies and get meta-data about types and CIL code of 
the methods. First option is to use reflection API that is 
available as a part of .NET base libraries. Second option is 
Microsoft Common Compiler Infrastructure (CCI), 
which is developed in Microsoft Research. 
Last option is Mono Cecil, which is developed as part of 
the Mono open-source project. 

\subparagraph*{}
Standard .NET Reflection API looks at assemblies as a code, not as a raw data, 
which has two important consequences: the code loaded through .NET Reflection 
API can be excecuted; and, because the code can be executed, the 
runtime must check access right and might throw Code Access Security exception. 
Assemblies loaded into an AppDomain (which is a .NET object similar to a 
process in a operating system) cannot be unloaded. Finally the .NET 
Reflection API does not distinguish between type definition a type reference, 
which is an entry in assembly metadata refering to a type located in another 
assembly. If we used the standard Reflection API, there would be one 
notable advantage. In the public API of Patterns4Net, in some cases, 
we allow to use the .NET Reflection data structures in order to make the 
usage of the Patterns4Net API easier for developers used to use the 
.NET Reflection. However, because we internally use another library, 
we have to do a translation of the .NET Reflection data structures.

\subparagraph*{}
The other two libraries (CCI and Mono Cecil) process .NET assemblies 
as just a binary data, hence they do not support loading the assemblies 
into AppDomain and execution of the loaded code. On the other hand 
they are claimed to be faster than the standard Reflection API, however 
we are not aware of any serious benchmarks. Public API and features 
of CCI and Mono Cecil seem to be similar, exept CCI provides AST over the 
intermediate language, which Mono Cecil doesn't 
provide\footnote{There is project Cecil Decompiler, but it not in production ready quality.}, 
however the AST the CCI generates is more complex than we would need, 
therefore, for our purposes, the advantage of generated AST would be lessen 
by extra work for it's processing. Both of these two libraries have a 
long list of advanced software that use them. In case of Mono Cecil it 
is, for example, db4o (object database for java and .NET) or Mono's C\# compiler. 
On the other side, FxCop (a bug-finding tool) or Code Contracts are both 
based on CCI.

\subparagraph*{}
Our previous experiences with Mono Cecil have resolved the choise between 
Mono Cecil and CCI in favour of Mono Cecil. This choice does 
not only influence the code that does the CIL analysis, but also other code 
because we use specific Mono Cecil's data structures 
(e.g., \inlinecode{TypeReference}) in whole Patterns4Net project. 

\paragraph{CIL analysis}

\subparagraph*{}
Cecil provides only data parsed from .NET assemblies, it does not provide 
anything more. From CIL meta-data we can, for example, determine for a 
given class what type is it's base type, or which interfaces it implements. 
But Cecil itself does not provide a method that would give us a list of 
types that implement given interface, because this information cannot be 
inferred directly from it's meta-data. For such purposes there is a project 
Mono Cecil Rocks, which contains a few extension methods for Cecil's 
classes, but it does not have all we wanted to support in Patterns4Net, 
so we also implemented our custom set of extension methods designed for 
CIL analysis and patterns structure constrains specification.

\subparagraph*{}
For example, one of the extensions we wanted to provide was uniform API 
for getting information about methods overrides. In CIL, according to ECMA CIL 
specification, there is an attribute "overrides" in 
meta-data of every method, which is a list of methods that this method overrides. 
But this attribute is used only in specific cases (e.g., explicit interface 
implementation) and normally it is left empty, because overridden methods 
are determined by conventions (which are also described in the ECMA CIL 
specification). 

\paragraph*{Methods invocation analysis}
\subparagraph*{}
For purposes of discovery of relationships in Architecture Explorer and 
methods invocations in Pattern Enforcer, we needed classes that would help us 
with analysis of CIL. We don't need to analyse conditional statements -- we 
just want to know whether method M1 on field F was invoked in body 
of method M2, even in dead branch of code.

\subparagraph*{}
Method calls in CIL are done by several instructions, for example 
\inlinecode{.callvirt}. CIL does not distinguish between instance methods 
and static methods. Instance methods has the instance as a first parameter, 
which is normally added by a compiler. Each of these instructions has a method 
reference as an argument, so the only difficulty is to analyse with which 
actual parameters the method was called.

\subparagraph*{}
CIL virtual machine is a stack based machine, which means that all arguments 
for operations are taken from the evaluation stack and result are 
pushed onto the stack. Usually instructions pop all their arguments from the 
stack and push results onto the top. Stack behaviour of each instruction is  
documented in the ECMA CIL specification, however Cecil provides this 
information through the enumeration \inlinecode{StackBehaviour}. 

\subparagraph*{}
The CIL analysis is done by simulating the evaluation stack. In loop we 
iterate over all instructions in the method body. For each instruction 
we determine how many items it pops from the stack and we determine, 
which items it pushes onto the stack. The stack is represented as 
a collection of instances of the \inlinecode{StackItem} class. 
Each \inlinecode{StackItem} has a reference to the instruction that 
resulted in pushing this item onto the stack, and with this basic information 
the \inlinecode{StackItem} can provide some more additional information such as 
whether it represents a field pushed onto the stack (if so, then which field), 
or a parameter aso. Result of this analysis is a collection of 
the \inlinecode{StackState} class instances -- n-th of them represents 
the state of the stack after the execution of n-th instruction in the method body. 
State of the stack is represented as a collection of \inlinecode{StackItem} instances.
From the signature of the method we know how many parameters it has 
(we will designate it as $m$) and whether it is an instance method 
or a static method. To get the actual parameters of a specific call 
instruction (say it's $n$-th instruction), we just need to take 
$m$ (or $m+1$ for instance methods, which have implicit first parameter) 
items from the top of the $n-1$-th \inlinecode{StackState}.

\subparagraph*{}
The last question may be whether this correctly simulates the stack 
if we do not take the control flow instructions into account (only their stack 
behaviour). An answer is provided by ECMA CIL specification, which reads
\begin{quotation}
Regardless of the control flow that allows execution to arrive there, 
each slot on the stack shall have the same data type at any given point 
within the method body.
\end{quotation}

\paragraph*{CIL patterns matching}
\subparagraph*{}
In order to check some more specific constraints such as the specification 
for the \pattern{Singleton} pattern implementation, we need to check whether 
method body contains a specific CIL instructions pattern\footnote{here the term 
pattern has a slightly different meaning than a design pattern.}.

\subparagraph*{}
The main class for CIL instructions patterns matching is 
\inlinecode{CILPatternsMatcher}. It aggregates a collection of instances of 
the \inlinecode{InstructionMatcher} abstract class, which controls 
the matching process. Interface of the \inlinecode{InstructionMatcher} class 
is shown in figure \ref{fig:instructionmatcher}. 
Method \inlinecode{Matches} is called in a loop on 
the current instruction. If the method returns \inlinecode{false}, than the 
CIL instructions does not match the pattern and the whole process ends with 
a negative result. Otherwise property \inlinecode{Found} is checked and if 
\inlinecode{true}, then the next \inlinecode{InstructionMatcher} is used in 
the next iteration, if it was the last \inlinecode{InstructionMatcher}, then 
process ends with success. In the next iteration current instruction is set to 
the one returned by last call of \inlinecode{Match}. Pseudo code is given in 
figure \ref{fig:matcherpseudocode}.

	\begin{figure}[h]
		\begin{minted}[bgcolor=codebg]{csharp}
public abstract class InstructionMatcher
{
	public virtual bool Found { get; protected set; }
	public abstract bool Matches(
		Instruction instruction, 
		out Instruction next);
	public virtual void Reset() { ... }
}
		\end{minted}
		\caption{The \inlinecode{InstructionMatcher} abstract class interface.}
		\label{fig:instructionmatcher}
	\end{figure}
	
	\begin{figure}[h]
		\begin{algorithmic}[1]
			\STATE $currentInstruction \gets$ first instruction of the method's body.
			\STATE $currentMatcherIdx \gets 0$
			\LOOP
				\STATE $matcher \gets matchers[currentMatcherIds]$
				\STATE $match \gets matcher.Match(currentInstruction, out\;next)$
				\IF{$not$ $match$}
					\RETURN $false$
				\ENDIF
				\IF{$matcher.Found$}
					\IF{$++currentMatcherIdx == matchers.Length$}
						\RETURN $true$
					\ENDIF
				\ENDIF
				\STATE $currentInstruction \gets next$
			\ENDLOOP
		\end{algorithmic}	
		\caption{Pseudo code of CIL instructions patterns matching.}
		\label{fig:matcherpseudocode}		
	\end{figure}	


%-------------------------------------------------------------------------------
%-------------------------------------------------------------------------------	
\subsection{Patterns representation and discovery}

\subparagraph*{}
Patterns representation is described in section \ref{sec:featurespatternenforcer}. 
Here we just remind that a pattern is represented as a CLR class derived from 
\inlinecode{PatternBase}. It contains properties representing the participants 
of the pattern and any other information that the pattern's author finds useful. 
Mono Cecils structures are used for types and methods identification. 

\subparagraph*{}
Discovery of patterns meta-data is implemented as a flexible 
mechanism. There is a central class named \inlinecode{PatternsLocator}, 
which aggregates objects that implement interface 
\inlinecode{IPatternsProvider}. Each of these objects provide a strategy 
method \inlinecode{GetPatterns}, which for given type or a method returns 
a list of patterns. The method or the type is then considered as a main 
role of the returned pattern instances. However, the pattern instances may 
contain other roles. The main role of a pattern is usually used in 
Pattern Enforcer's error messages, in the section about Architecture Explorer 
we also refer to this term several times.

\subparagraph*{}
The two implementations of \inlinecode{IPatternsProvider} 
that are supplied with Patterns4Net provide location of patterns meta-data 
based on Patterns4Net attributes. Diagram in the figure \ref{fig:patternslocation} shows 
the class hierarchy. The collection of \inlinecode{IPatternsProvider} 
instances is supplied to the \inlinecode{PatternsLocator} class as constructor 
parameter. The \inlinecode{PatternsLocator} class is usually constructed 
via MEF container and thus the constructor parameter is resolved 
automatically by MEF. If we want an instance of some class to be registered in 
the container as \inlinecode{IPatternsProvider} implementor, the only thing we have to do 
is to decorate such class with attribute \inlinecode{[Export(typeof(IPatternsLocator))]}.

\begin{figure}[h]
  \mbox{\includegraphics[width=120mm]{images/patterns-location.eps}}
  \caption{Hierarchy of classes that are used for discovery of patterns meta-data.}
  \label{fig:patternslocation}
\end{figure}

\subparagraph*{}
The \inlinecode{PlainAttributesPatternProvider} and 
\inlinecode{AttributesPatternProvider} classes responsibility is to 
transform CIL meta-data information about attributes 
into objects that represent the discovered patterns. 
This task is not as easy as it may seem. 

\subparagraph*{}
Firstly classes that represent the Pattern4Net attributes are not identical 
to classes that represent the patterns. This decoupling provides flexibility, 
because patterns meta-data does not have to be based only on attributes, 
but in this case it causes some additional work to be done.

\subparagraph*{}
Secondly CIL meta-data parsed by Mono Cecil are not real instances of the 
classes that represent Patterns4Net attributes. Rather Mono Cecil provides 
information about what the type of the attribute is, which values are 
provided as it's constructor parameters and which named arguments were 
provided. If the user of Mono Cecil wants to construct an identical instance 
of the attribute, he has to do it by hand. Actually the 
\inlinecode{PlainAttributesPatternProvider} class even does not 
have to construct Patterns4Net attributes instances, 
instead the \inlinecode{PlainAttributesPatternProvider} class constructs 
objects representing the patterns directly. 

\subparagraph*{}
There are two basic options to solve this task. We could say that 
Pattern4Net attributes should always implement a constructor with 
name-value dictionary as a parameter. The constructor would reconstruct the 
attribute object from this dictionary. (This approach is also used in the MEF.) 
Finally the attribute object itself would represent the pattern instance. 
The other option is to absolutely decouple the creation of an object 
representing the pattern and the attribute itself. In this case, 
there would be a separate class that would construct the object representing 
the pattern instance from Cecil's meta-data structures and the attribute 
would be just a dummy data holder. 

\subparagraph*{}
First option provides higher cohesion -- we don't have to create another class, 
but the attribute and the process of creation of an object representing the 
pattern are coupled. This approach could be suitable for scenario when a user 
wants to implement his custom pattern and so Patterns4Net provide this possibility, 
which is implemented in the \inlinecode{AttributesPatternProvider} class.
But internally Patterns4Net uses the former approach, because it 
cuts down the code needed in Pattern4Net attributes classes and thus 
minimizes the footprint of the assembly containing Pattern4Net attributes, which 
has to be referenced by a project that makes use of Pattern4Net. The former 
approach is implementd in \inlinecode{PlainAttributesPatternProvider}.

%\subparagraph*{}
%\todo{Usage of MEF metadata...?}

%-------------------------------------------------------------------------------
%-------------------------------------------------------------------------------
\subsection{Pattern Enforcer Design}

\subparagraph*{}
The basic interface in the Pattern Enforcer design is generic 
\inlinecode{IChecker<T>} interface, which defines one method 
\inlinecode{Check(T)}. This method returns the result of the 
check encapsulated in an instance of the \inlinecode{CheckerResult} 
class. Concrete checkers have the generic parameter \inlinecode{T} 
set to the \inlinecode{TypeDefinition} class, 
the \inlinecode{MethodDefinition} class or the \inlinecode{PatternBase} class.

\subparagraph*{}
An important class is the \inlinecode{FluentPatternChecker}. It is a base 
class of most of the pattern checkers, because it provides the structural 
constraints specification DSL. The DLS is formed by protected methods of 
the \inlinecode{FluentPatternChecker} class, which should be invoked in the 
constructor of derived class in order to specify the constraints. 
Because we wanted to provide a Fluent interface (chaining of method calls), 
these methods return special objects that have 
\begin{itemize}
	\item{a reference a to the parent object and}
	\item{the values of the arguments the method was invoked with.}
\end{itemize}
For the first method in a chain the parent object is the checker instance itself, 
for others, it is a object returned by their ancestor method 
in the chain. As the method calls are chaining the arguments are collected 
and the last method in the chain, which is the first method that wil actually 
do something has all the arguments of previous methods available to do 
it's work. The example of such chaining of methods is given in example 
\ref{fig:chaining}.

	\begin{figure}[h]				
		\begin{minted}[bgcolor=codebg]{csharp}
this.Type(pattern => pattern.PatternRoleType)	
	.Methods(method => method.IsPublic || method.IsProtected) 
	.Check((pattern, method) => method.Name.EndsWith("42"),
		(pattern, method) => "Method has not a valid name");
		\end{minted}		
		\caption{An example of methods chaining.}
		\label{fig:chaining}
	\end{figure}

\subparagraph*{}
The whole Pattern Enforcer is encapsulated as the \inlinecode{PatternEnforcer} 
class. It requires a \inlinecode{PatternsLocator} instance and an array of 
\inlinecode{IPatternCheckersLocator} instances. These classes have also their 
dependencies requested as constructor arguments so composition of all the 
objects by hand would be tedious. Instead the composition capabilities of 
the MEF are employed. A type whose instance should be used anywhere the 
interface \inlinecode{IFace} is expected must be decorated with attribute 
\inlinecode{[Export(typeof(IFace))]}, dependencies of such type will be 
resolved by MEF recursively.


%-------------------------------------------------------------------------------------------------
%-------------------------------------------------------------------------------------------------
%-------------------------------------------------------------------------------------------------
\section{Comparison}

\paragraph{FxCop and Gendarme tools.}
\subparagraph*{}
It may not be obvious at the first look, but Pattern Enforcer is similar 
to static analysis bug-hunting tools such as FxCop or Gendarme 
(\cite{gendarme:Online}). These tools 
search the source code for idioms that are generaly considered as bad. For 
example strings should be, in most cases, compared using 
\inlinecode{string.CompareOrdinal}, but not using \inlinecode{==} operator. 
There are two main differences between Pattern Enforcer and these tools
\begin{itemize}
	\item{Pattern Enforcer checks only code that is annotated,}
	\item{Pattern Enforcer checks structural aspects and code idioms, 
	but Gendarme and FxCop check only code idioms.}
	\item{Gendarme and FxCop are looking for bad idioms, but 
	Pattern Enforcer is verifies that expected idiom is present.}
\end{itemize}

\subparagraph*{}
Gendarme is open-source tool that is ment to be an alternative to FxCop. 
It uses Mono Cecil for CIL analysis. If we look at Gendarme's source code, 
it has a similar structure to Pattern Enforcer's code. 
It has also "checker" classes, that perform checks on a code element,  
which might be, for example, Cecil's \inlinecode{TypeDefinition}. 

\paragraph*{A Pattern Enforcing Compiler (PEC) for Java.}
\subparagraph*{}
Because a Pattern Enforcing Compiler (PEC) for Java (\cite{lovatt2007pattern}) 
has been the main source of inspiration for our thesis, we discuss it a 
little bit more in detail. 

\subparagraph*{}
PEC for Java is an extended Java compiler that formalizes patterns. 
Developers can use standard Java syntax to annotate their classes as an 
implementation of specific design pattern. The PEC than checks whether 
the classes actually implement specified patterns.

\subparagraph*{Annotation.} For annotation of patterns instances, 
PEC uses so called marker interfaces. The authors have choosen this technique, 
because implemented interfaces are listed in generated API documentation 
and so an intergration with an API documentation didn't require any 
additional work to be done. On contrary, interfaces can only be used for 
annotation of classes, but not methods, and even when interfaces can have 
arguments -- generic arguments --, these can capture only limited number 
of additional information. Authors of PEC admit these weakneses of 
interfaces as a technique for the annotation of patterns and 
in \cite{lovatt2007pattern}, they propose to introduce the standard 
java annotations, similar to .NET attributes, in PEC. However, 
we are not aware of any updated version of PEC that uses stndard Java annotations.

\subparagraph*{Pattern Enforcement.}
PEC uses static analysis and it also enforces the rules dynamicaly by 
inserting assertions into the resulting program, which we don't support 
in our Pattern Enforcer. Dynamical enforcement 
provides more accurate results, because, for example, uniqueness of 
the one \pattern{Singleton} instance cannot be proved statically, but 
dynamically one simple assetion is enough to enforce it. The disadvantage 
of dynamical enforcement is that it slows down the resulting program and to 
discover bugs the program still has to be manually tested.

\subparagraph*{Code generation.}
PEC provides also code generation capabilies. For example, a body of a void method 
in a \pattern{Composite} class can be generated by PEC -- it will just 
create a loop over all components and on each of them it invokes the 
corresponding method. However, an implementation of the \pattern{Composite} 
pattern is usualy not so straightforward, so these capabilities turn to be not 
so useful.

\subparagraph*{Patterns specification.}
Two APIs for patterns specification are supported in PEC. It is standard 
Java reflection API and Javaasist, which is similat to Mono Cecil. In Pattern 
Enforcer we support the standard .NET reflection only partly. In PEC a method 
that checks a pattern implementation must be a static method with specific signature 
declared in a marker interface of the pattern. This introduces coupling 
between a pattern annotation and a pattern enforcement, which we tried to 
avoid in Patterns4Net. PEC uses exceptions to to signal the errors during 
the check of pattern implementation. This means that usually when first 
violation is found, an exception is thrown and the verification process does 
not continue. In our Pattern Enforcer we use a return value of special type 
\inlinecode{CheckerResult} as the result of the check and this 
object can aggregate more errors.

\subparagraph*{Integration with development environment.}
The authors of PEC claim that it is an extended compiler, which means that 
Java source code is compiled only with PEC, although PEC internally uses 
\inlinecode{javac}. This provides seamless integration with the Java 
environment, but at the same moment PEC becomes an essential requirement for 
successful build. Our Pattern Enforcer is standalone tool, which can be 
easily taken out from the build process. PEC does not provide any other 
usage possibilities, but our Pattern Enforcer has a MSBuild task and 
unit-testing API.

\paragraph*{Other tools.}
\subparagraph*{}
CoffeeStrainer (\cite{bokowski1999coffeestrainer}) is a tool that is somewhere 
between static analysis bug-hunting tools whose objects of interrest are idioms, 
smaller pieces of code, and pattern enforcement tools. Unlike other 
static analysis bug-hunting tools CoffeeStrainer enforces rules that result 
from paticular design desions, for this it provides means for custom 
rules specificatoin.

\subparagraph*{}
Pattern-Lint (\cite{sefika1996monitoring}) can check conformance to variety 
of design principles from coding style rules to design patterns. 
Pattern-Lint targets C++ and has been successfuly evaluated during development 
of a multimedia operating system.

\subparagraph*{}
Most of the approaches described in \cite{taibi2007design} are connected with 
some prototype tool that enforces the specification represented accoring to 
the formalization approach. 
However, most of them are not publicly available and all of them target 
either Java or C++ languages. The most interesting tools from this book include 
the HEDGEHOG engine, which we discuss also in section \ref{sec:patterns-formalization}, 
and tools that come with LePUS3, which we also present in the same section. 






